package com.daoshu.mds.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.mds.resource.mapper.ClustersGroupMapper;
import com.daoshu.mds.resource.service.IClustersClientService;
import com.daoshu.mds.resource.service.IClustersGroupService;
import com.daoshu.resource.bo.ClustersGroupBo;
import com.daoshu.resource.entity.ClustersClientEntity;
import com.daoshu.resource.entity.ClustersGroupEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ClustersGroupServiceImpl extends ServiceImpl<ClustersGroupMapper, ClustersGroupEntity> implements IClustersGroupService {

	@Autowired
	private IClustersClientService clustersClientService;
	
	@Override
	public ClustersGroupEntity getDetailById(String id) {
		ClustersGroupEntity entity = this.getById(id);
		entity.setChildren(clustersClientService.list(new QueryWrapper<ClustersClientEntity>().eq("group_id_", id)));
		return entity;
	}
	
	@Override
	public IPage<ClustersGroupEntity> getPage(ClustersGroupBo clustersGroupBo) {
		ClustersGroupEntity entity = new ClustersGroupEntity();
		BeanUtils.copyProperties(clustersGroupBo, entity);
		IPage<ClustersGroupEntity> page = this.page(new Page<>(clustersGroupBo.getStart(), clustersGroupBo.getSize()), new QueryWrapper<ClustersGroupEntity>(entity));
		if (page.getRecords().size() > 0) {
			Set<String> ids = new HashSet<String>();
			page.getRecords().forEach(item -> {ids.add(item.getId());});
			List<Map<String, Object>> maps = clustersClientService.listMaps(new QueryWrapper<ClustersClientEntity>().select("group_id_ groupId, count(id_) count").in("group_id_", ids).groupBy("group_id_"));
			Map<String, Integer> idToCount = convertToCount(maps);
			page.getRecords().forEach(item -> {
				if (idToCount.containsKey(item.getId())) {
					item.setCount(idToCount.get(item.getId()));
				}
			});
		}
		return page;
	}
	
	private Map<String, Integer> convertToCount(List<Map<String, Object>> maps) {
		Map<String, Integer> result = new HashMap<String, Integer>();
		for (Map<String, Object> map : maps) {
			result.put(map.get("groupid").toString(), Integer.parseInt(map.get("count").toString()));
		}
		return result;
	}
}
